package hn.cch.performance.excutor;

import org.slf4j.MDC;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池
 */
public class MyThreadPoolExecutor extends ThreadPoolExecutor {


    public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                                TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    public void execute(@NonNull Runnable command) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        Runnable runnable = () -> {
            if (!CollectionUtils.isEmpty(contextMap)) {
                MDC.setContextMap(contextMap);
            }
            try {
                command.run();
            } finally {
                MDC.clear();
            }
        };
        super.execute(runnable);
    }

}
